package edu.cug.water.crawler.job.task.committee;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import edu.cug.water.crawler.common.annotation.BeanField;
import edu.cug.water.crawler.common.constant.Constant;
import edu.cug.water.crawler.common.constant.EsConstants;
import edu.cug.water.crawler.common.exception.RRException;
import edu.cug.water.crawler.common.utils.DateUtils;
import edu.cug.water.crawler.common.utils.EsUtils;
import edu.cug.water.crawler.job.entity.committee.pearl.PearlWater;
import edu.cug.water.crawler.job.entity.committee.pearl.ReservoirOfPearlWater;
import edu.cug.water.crawler.job.entity.committee.pearl.RiverOfPearlWater;
import edu.cug.water.crawler.job.request.RequestUtil;
import edu.cug.water.crawler.job.task.ITask;
import edu.cug.water.crawler.job.utils.AbstractCrawlerTask;
import edu.cug.water.crawler.job.utils.DataConvertUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Component("job:PearlWater")
@Slf4j
public class PearlWaterTask extends AbstractCrawlerTask<PearlWater> implements ITask {

    @Autowired
    private EsUtils esUtils;

    @Autowired
    private RequestUtil requestUtil;

    @Override
    public int run(String params) throws IOException {
        init();

        url = "http://www.pearlwater.gov.cn/switch/" + params.trim() + "/list?Ew5cLV66=5KkP6qPovLWDnIeXKCWaZ2MFzu78ekMQG19eP_M.3hxhBUjxMidL90myBBwLhncK0zYsP3bj7JoeGChFDLxlfnHgw0RgtReRqFjBDStmnywLX5QROP67HEch7C8_eiajVpIxA536ct.IMgpkx13TT55MQlNJJJFaFiZcqvfsfOdS4aqp3YiOIRqkGOZOvG0cr_TI2Sm0OO2V3xxZPzdXYmjmuqETqq8x9vZpwti3O68KumhSAkJB2UUD6b.vX7MZaWY9tp_uycSyUKwSmu5Epmnk7QibI2V_2SfvV7t9U_.saNkTTVVJDh4WTUdOk7mvpKz70HXl6U9VCOIbJacfF.A&c4Lc11xd=4ENYHQ4cMzxEz90E9Bjsh2r6AD0qBDdfnXR.YvO3uPXcgmkPsihaMXXPNb38xekrXZFIQNBipfx6OV1g17VmwHWzZ3TBVxnMn2bT7JJwQkj2iMGuiyLCVGl8BoeoAhSo0BT8IUzwHJHU.lCxj5P3gwOruadr5IGQQEGhZhV19Pua";

        if (!("river".equals(params) || "rsvr".equals(params))) {
            throw new RRException(getClass().getName() + Constant.LogConstants.TASK_PARAMS_IS_WRONG + " :" + params);
        }
        return request(params);
    }

    @Override
    protected void init() {
        super.init();
        headers.set("Host", "www.pearlwater.gov.cn");
        headers.set("Connection", "keep-alive");
        headers.set("Accept", "application/json, text/javascript, */*; q=0.01");
        headers.set("X-Requested-With", "XMLHttpRequest");
        headers.set("Origin", "http://www.pearlwater.gov.cn");
        headers.set("Referer", "http://www.pearlwater.gov.cn/sssq/");
        headers.set("Accept-Encoding", "gzip, deflate");
        headers.set("Accept-Language", "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7");
        headers.set("Cookie", "Secure; C1N17nSnpOUPS=5zqibQG8.QiqbWmj.XVtOY4Nl2Rrs9DIyC1tvwK_.SIOb6ZVxS29rUWmJ1UL0FLv9Rgac3IQZojKhrjzuxGcjsA; Secure; _gscu_1651062306=00805546ntozl371; _gscbrs_1651062306=1; C1N17nSnpOUPT=5RKq_IDYGiZGqqqDhd5pTqqjGfsl4qj7ICqnIVTxihax5m04DJSvxQ4mejdice7yKUzRLGq.4pgriXQ6RKwPM.ik3AIdbaZTy5iGMrQSFMJQg1u2G__nBj.fZt144XwgntzLM6hMD1f57PDK6afQGajYaGgh4bnToltMF5SWEwKujiy8OAH0s6fYTetMQ_qAvlnHtLrOOOXy2I8C1hh7y.O1yLmCFrrLtztGqKw4BiHdutt0yaPbRCmnnwt5s5vB8xuZGyDx.ev6BpgWmgjxsNv; _gscs_1651062306=00805546k2zwa071|pv:3");

        multiValueMap.put("Ew5cLV66", Collections.singletonList("5KkP6qPovLWDnIeXKCWaZ2MFzu78ekMQG19eP_M.3hxhBUjxMidL90myBBwLhncK0zYsP3bj7JoeGChFDLxlfnHgw0RgtReRqFjBDStmnywLX5QROP67HEch7C8_eiajVpIxA536ct.IMgpkx13TT55MQlNJJJFaFiZcqvfsfOdS4aqp3YiOIRqkGOZOvG0cr_TI2Sm0OO2V3xxZPzdXYmjmuqETqq8x9vZpwti3O68KumhSAkJB2UUD6b.vX7MZaWY9tp_uycSyUKwSmu5Epmnk7QibI2V_2SfvV7t9U_.saNkTTVVJDh4WTUdOk7mvpKz70HXl6U9VCOIbJacfF.A"));
        multiValueMap.put("c4Lc11xd", "4ENYHQ4cMzxEz90E9Bjsh2r6AD0qBDdfnXR.YvO3uPXcgmkPsihaMXXPNb38xekrXZFIQNBipfx6OV1g17VmwHWzZ3TBVxnMn2bT7JJwQkj2iMGuiyLCVGl8BoeoAhSo0BT8IUzwHJHU.lCxj5P3gwOruadr5IGQQEGhZhV19Pua");
    }

    public int request(String params){
        ResponseEntity<String> response = getRequestBody();
        if (StringUtils.isEmpty(response)) {
            throw new RRException(getClass().getName() + Constant.LogConstants.RESPONSE_IS_NULL.getValue());
        }
        List<PearlWater> list = parse(params, response.getBody());
        log.info("{} converts results：{}", getClass().getName(), list.size());

        String s = esUtils.addDocuments(EsConstants.TypeConstant.PEARL_WATER_.getValue() + params.toLowerCase(), list);
        Boolean aBoolean = esUtils.statusJudge(s);
        if (!aBoolean) {
            throw new RRException(getClass().getName() + Constant.LogConstants.THE_PROCESS_OF_ES_STORE_FAILED.getValue());
        }
        return list.size();
    }

    private List parse(String param, String body) {
        JSONObject jsonObject = (JSONObject) JSONObject.parse(body);
        int status = jsonObject.getIntValue("code");
        String msg = jsonObject.getString("msg");
        log.info("PearlWater {} Request Data status: {}, {}", param, status, msg);

        List results = new ArrayList<>();

        JSONArray data = jsonObject.getJSONArray("data");
        for (Object datum : data) {
            JSONObject temp = (JSONObject)datum;
            Class<?> aClass = null;
            if ("river".equals(param)) {
                aClass = RiverOfPearlWater.class;
            } else if ("rsvr".equals(param)) {
                aClass = ReservoirOfPearlWater.class;
            }
            try {
                Object o = aClass.newInstance();
                Field[] old = aClass.getDeclaredFields();

                Field[] fields = (Field[]) ArrayUtils.addAll(old, aClass.getSuperclass().getDeclaredFields());
                for (Field field : fields) {
                    BeanField annotation = field.getAnnotation(BeanField.class);
                    field.setAccessible(true);

                    if (annotation == null) field.set(o, DateUtils.formatDateTime(new Date()));
                    else field.set(o, (temp.get(annotation.property()) + "").trim());

                    if ("stationCode".equals(field.getName())) field.set(o, DataConvertUtil.stationCodeConvert((temp.get(annotation.property()) + "").trim()));
                }
                results.add(o);
            } catch (InstantiationException e) {
                throw new RRException("InstantiationException " + e.getMessage());
            } catch (IllegalAccessException e) {
                throw new RRException("IllegalAccessException" + e.getMessage());
            }
        }
        return results;
    }

    @Override
    public ResponseEntity<String> getRequestBody() {
        return requestUtil.post(url, headers, multiValueMap);
    }

    @Override
    public List<PearlWater> getDataFromStr(String requestBody) {
        return null;
    }
}
